// import { TButton, TDialog, TPopupProxy, TTable } from 't';
import TButton from 't/basic/button';
import TDialog from '@teld/q-components/Dialog';
import TPopupProxy from 't/basic/popup-proxy';
import TTable from 't/basic/table';
import { computed, defineComponent, onMounted, ref, toRefs, watch } from 'vue';
import HistoryComponent from './HistoryComponent';
import PreviewResult from './PreviewResult';
import SearchResult from './SearchResult';
import SingleRow from './SingleRow';
import { useQuasar } from '@teld/q-components';
export default defineComponent({
  name: 'SelectHelperSmallSizeRender',
  components: {
    TPopupProxy,
    TTable,
    HistoryComponent,
    SingleRow,
    TButton,
    TDialog,
    PreviewResult,
    SearchResult,
  },
  props: {
    simple: {
      type: Boolean,
      default: true,
    },
    width: {
      type: [String, Number],
      default: '1',
    },
    multiple: Boolean,
    height: String,
    position: String,
    historyEnable: Boolean,
    value: {
      type: [Array, String],
    },
    checkList: {
      type: [Array, String, Object],
    },
    columns: {
      type: Array,
    },
    valueField: String,
    labelField: String,
    helperCode: String,
    placeholder: String,
    searchEnable: Boolean,
    searchPosition: String,
    subsidiary: String,
    countPerPage: String,
    pagination: Boolean,
    iconEnable: Boolean,
    iconDataSource: String,
    iconFiled: String,
    maxCheckedLength: [String, Number],
    showChecked: Boolean,
    isCloseIng: Boolean,
    label:String
  },
  emits: ['update:checkList', 'update:isCloseIng'],

  setup(props, { attrs, emit, expose, slots }) {
    const refComponent = ref();
    const $q = useQuasar();
    const {
      simple,
      width,
      multiple,
      height,
      position,
      historyEnable,
      value,
      checkList,
      columns,
      valueField,
      labelField,
      helperCode,
      placeholder,
      searchEnable,
      searchPosition,
      subsidiary,
      countPerPage,
      pagination,
      iconEnable,
      iconDataSource,
      iconFiled,
      maxCheckedLength,
      showChecked,
      label,

    } = toRefs(props);

    const refTPopupProxy = ref(null);
    const selection = ref([]);

    const show = () => {
      refTPopupProxy.value&&refTPopupProxy.value.show();
    };
    const close = () => {
      emit('update:isCloseIng', true);
      refTPopupProxy.value&&refTPopupProxy.value.hide();
      setTimeout(() => {
         emit('update:isCloseIng', false);
      }, 1000);
    };
    const filter = ref('');
    const getDateByFilter = () => {
      if (rows.value && rows.value == 1) {
        selectList.value = rows.value;
        emit('update:checkList', selectList.value);
        close();
      }
    };
    expose({
      show,
      close,
      getDateByFilter,

    });
    onMounted(() => {});

    function onClickHandler(params) {}
    //简单模式
    const columnsByComputed = computed(() => {
      return columns.value && columns.value.length > 0
        ? columns.value
            .map(item => {
              if (item.isShow && item.dataField == labelField.value) {
                return {
                  name: item.dataField,
                  required: true,
                  label: item.caption,
                  align: item.textAlign ? item.textAlign : 'left',
                  field: item.dataField,
                  width: item.width ? item.width : '',
                  // sortable: true,
                  // sort: (a, b) => parseInt(a, 10) - parseInt(b, 10),
                };
              }
            })
            .filter(item => item)
        : [
            {
              name: labelField.value,
              required: true,
              label: labelField.value,
              align: 'left',
              field: labelField.value,
              width: '',
              // sortable: true,
              // sort: (a, b) => parseInt(a, 10) - parseInt(b, 10),
            },
          ];
    });
    const computedHeight = computed(() => {
      let _height = height.value ? height.value : '80vh';
      if (_height.indexOf('%') > -1) {
        _height = _height.replace('%', 'vh');
      }
      return _height;
    });
    const generateSimple = () => {
      return (
        <single-row
          width={'100vw'}
          multiple={multiple.value}
          simple={simple.value}
          onUpdateSelectList={e => {
            selectList.value = e;
          }}
          checkList={selectList.value}
          placeholder={placeholder.value}
          columns={columnsByComputed.value}
          labelField={labelField.value}
          valueField={valueField.value}
          filter={filter.value}
          subsidiary={subsidiary.value}
          ref={refComponent}
          countPerPage={countPerPage.value}
          pagination={pagination.value}
          iconEnable={iconEnable.value}
          iconDataSource={iconDataSource.value || iconFiled.value}
          targetSelection={selection.value}
          targetSelectList={selectList.value}
          height={computedHeight.value}
          style='flex:1;overflow:auto;'
        />
      );
    };
    //已选择数据集合
    const selectList = ref([]);
    // watch(
    //   () => value.value,
    //   () => {
    //     //计算当前数据，实现数据回显
    //     selectList.value = value.value;
    //   },
    // );
    watch(
      () => selectList.value,
      () => {
        if (multiple.value) {
          selection.value = selectList.value.map(
            item => item[valueField.value],
          );
          return;
        }
        emit('update:checkList', JSON.parse(JSON.stringify(selectList.value)));
        close();
        // emit('update:value', selectList.value);
      },
      {
        deep: true,
        // immediate: true,
      },
    );
    const selectList_proxy = ref([]);
    watch(
      () => checkList.value,
      () => {

        if (JSON.stringify(selectList.value) == JSON.stringify(checkList.value))
          return;
        //计算当前数据，实现数据回显
        if (!simple.value) {
          selectList_proxy.value = checkList.value;
          selectList.value = JSON.parse(JSON.stringify(selectList_proxy.value));
        } else {
          selectList.value = JSON.parse(JSON.stringify(checkList.value));
        }
      },
      {
        deep: true,
        immediate: true,
      },
    );
    //定义点击事件
    const trTargetClick = target => {
      if (selectList.value.some(item => item.name == target.name)) {
        selectList.value = selectList.value.filter(
          item => item.name != target.name,
        );
      } else {
        if (!multiple.value) {
          selectList.value = [];
        }
        selectList.value.push(target);
      }
    };
    const checkAll = computed(() => {
      if (rows.every(item => selection.value.some(sel => item.name == sel))) {
        return ['ischecked'];
      } else if (
        !rows.some(item => selection.value.some(sel => item.name == sel))
      ) {
        return [];
      }
      return null;
    });
    if (multiple.value) {
      watch(
        () => selectList.value,
        () => {
          console.log(selectList.value);
          selection.value = selectList.value.map(
            item => item[valueField.value],
          );
        },
        {
          // immediate: true,
          deep: true,
        },
      );
    }

    //生成内容区域
    const generateContent = () => {
      if (isShow.value) {
        return generateSimple();
      } else {
        return (
          <div style={'height:var(--t-client-height);flex:1 1 aut;'}>
            <t-inner-loading
              showing={true}
              label={$q.lang.mixedView.chartLoading}
              label-class='text-teal'
              label-style='font-size: 1.1em'
            />
          </div>
        );
      }
    };
    const refPreview = ref();
    const refSearch = ref();
    const isShow = ref(false);
    return () => {
      return (
        <div>
          <search-result
            position={position.value}
            ref={refSearch}
            placeholder={placeholder.value}
            columns={columnsByComputed.value}
            labelField={labelField.value}
            valueField={valueField.value}
            v-model:checkList={selectList.value}
            multiple={multiple.value}
            pagination={pagination.value}
            countPerPage={countPerPage.value}
            historyEnable={historyEnable.value}
            helperCode={helperCode.value}
            iconEnable={iconEnable.value}
            iconDataSource={iconDataSource.value || iconFiled.value}
          ></search-result>
          <preview-result
            position={position.value}
            ref={refPreview}
            v-model:list={selectList.value}
            width={'100vw'}
            multiple={multiple.value}
            simple={simple.value}
            placeholder={placeholder.value}
            columns={columnsByComputed.value}
            labelField={labelField.value}
            valueField={valueField.value}
          ></preview-result>
          <t-dialog
            ref={refTPopupProxy}
            class='select_helper_popup select_helper_popup_m'
            position={position.value}
            // 如果设置为false 组件限制无法全屏
            maximized={position.value == 'right'}
            onBeforeShow={() => {
              isShow.value = true;
            }}
            onBeforeHide={() => {
              close();
              filter.value = '';
            }}
            onClick={e => {
   
              // e.stopPropagation();
              // e.preventDefault();

              // return false;
            }}
          >
            <div
              style={
                `height:${position.value == 'right' ? 'var(--t-client-height)' : computedHeight.value};` +
                'width:100vw;background:#fff;display: flex; flex-direction: column;'
              }
            >
              <header>
              <i
                  class={'fas dx-icon icon-t-delete-01'}
                  onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    close();
                    return false;
                  }}
                ></i>
                <span>{label.value}</span>
                {(() => {
                  if (searchEnable.value && searchPosition.value == 'top') {
                    return (
                      <t-button
                        class='right'
                        flat
                        round
                        dense
                        icon='search'
                        onClick={() => {
                          refSearch.value.show();
                        }}
                      />
                    );
                  }
                })()}
                {/* `${TComponents?.IconList?.common??'fas dx-icon'} ${TComponents?.IconList?.arrowLeft??'icon-t-arrow-left'}` */}
               
                
              </header>

              <div class={'display: flex;flex-direction: inherit;'}></div>
              {(() => {
                if (searchEnable.value && searchPosition.value == 'bottom') {
                  return (
                    <div style={'padding:0px 16px'}>
                      <t-input
                        class='tr-input-search'
                        borderless
                        outlined={false}
                        dense='dense'
                        clearable
                        labelPosition='left'
                        placeholder={placeholder.value}
                        v-model:modelValue={filter.value}
                        style='margin:6px 0'
                        tabIndex="0"
                        onKeydown={(event) => {
                          if (event&&event.key === 'Enter') {
                            event.preventDefault();
                            // 这里可以添加你的自定义逻辑
                          }
                        }}
                      >
                        {{
                          prepend: () => {
                            return (
                              <t-icon
                                name='search'
                                class='cursor-pointer'
                               style='font-size:16px;margin:0 4px 0 8px'
                              />
                            );
                          },
                        }}
                      </t-input>
                    </div>
                  );
                }
              })()}
              {(() => {
                if (
                  historyEnable.value &&
                  ((searchEnable.value && searchPosition.value == 'bottom') ||
                    !searchEnable.value)
                ) {
                  return (
                    <history-component
                      labelField={labelField.value}
                      valueField={valueField.value}
                      helperCode={helperCode.value}
                      filter={filter.value}
                      onClickByTag={e => {
                        if (!multiple.value) {
                          selectList.value = [];
                        }
                        if (
                          selectList.value &&
                          !selectList.value.some(
                            item =>
                              item[valueField.value] == e[valueField.value],
                          )
                        ) {
                          selectList.value.push(e);
                        }
                        emit('update:checkList', selectList.value);
                        close();
                      }}
                    ></history-component>
                  );
                }
              })()}

              {generateContent()}

              {(() => {
                if (multiple.value) {
                  return (
                    <div class='select_helper_popup_footGroup'>
                      {(() => {
                        if (showChecked.value) {
                          return (
                            <p class='select_helper_popup_footGroup_checkContent'>
                              <span>
                                {$q.lang.selectHelper.checked}
                                {(() => {
                                  if (selectList.value.length > 0) {
                                    return `(${selectList.value.length}):`;
                                  }
                                })()}
                              </span>
                              <span class='select_helper_popup_footGroup_checkContent_content'>
                                <span>
                                {(() => {
                                  return selectList.value
                                    .map(item => item[labelField.value])
                                    .map(items => items.replace(/,/gi, '，'))
                                    .join(',');
                                })()}
                                </span>
                               
                                  {(() => {
                                if (selectList.value.length > 0) {
                                  return (
                                    <t-button
                                      flat
                                      round
                                      dense
                                      icon='keyboard_arrow_up'
                                      onClick={() => {
                                        refPreview.value.show();
                                      }}
                                    />
                                  );
                                }
                              })()}
                              </span>
                            
                            </p>
                          );
                        } else {
                          return (
                            <t-button
                              align='center'
                              class='btn-fixed-width'
                              style='width:30%'
                              onClick={() => {
                                close();
                              }}
                            >
                              {$q.lang.label.cancel}
                            </t-button>
                          );
                        }
                      })()}

                      <t-button
                        align='center'
                        class='btn-fixed-width'
                        color='primary'
                        style={showChecked.value ? 'width:30%' : 'width:70%'}
                        onClick={() => {
                          if (
                            selectList.value.length > maxCheckedLength.value &&
                            maxCheckedLength.value != ''
                          ) {
                            return Funcs.Notify(
                              $q.lang.selectHelper.warning,
                              //'最多选择' + maxCheckedLength.value + '项',
                              //'最多只能选择{0}项',
                              $q.lang.selectHelper.maxCheckWarningMessage.format(
                                maxCheckedLength.value,
                              ),
                              'warning',
                            );
                          }
                          emit('update:checkList', selectList.value);
                          close();
                        }}
                      >
                        {$q.lang.label.ok}
                        {maxCheckedLength.value != ''
                          ? selectList.value.length +
                            '/' +
                            maxCheckedLength.value
                          : ''}
                      </t-button>
                    </div>
                  );
                }
              })()}
            </div>
          </t-dialog>
        </div>
      );
    };
  },
});
